#!/bin/bash
set -e
set -x
MYDIR="${0%/*}"
cd "$MYDIR/.."
source "recipes/common.sh"


# RECIPE START distimage
# depends: cross-grub
# depends: dosfstools-native
# depends: e2fsprogs-native
# depends: firmware-linux 
# depends: initramfs
# depends: mtools-native
# depends: rootfs
# depends: util-linux-native

if [ "x${BLINUX_BUILD_ID}" = 'x' ]; then
	BLINUX_BUILD_ID=$(git rev-parse HEAD)
fi
if [ "x${BLINUX_BUILD_DATE}" = 'x' ]; then
	BLINUX_BUILD_DATE=$(env LC_ALL=C date +%Y%m%d)
fi

IMG="blinux-${TARGET%%-*}-${BLINUX_BUILD_ID}.img"
IMG_LINK="blinux-${TARGET%%-*}-${BLINUX_BUILD_DATE}.img"
IMG_SIZE=8192 # MB
ESP_SIZE=127 # MB
ESP_OFFSET=1 # MB
ROOTFS_LABEL=BoringLinux
BOOTLOADER_ID=boringlinux

GRUB_BUILTIN_MODULES='configfile echo ext2 fat linux normal part_gpt search_fs_uuid search_label'


vdisk_size=$((IMG_SIZE*2048)) # measured in 512-bytes sectors
esp_size=$((ESP_SIZE*2048))
esp_offset=$((ESP_OFFSET*2048)) # measured in 512-bytes sectors
# Note: reserve 1 MB at the end of the disk for a GPT copy
rootfs_size=$((vdisk_size-esp_size-2*esp_offset)) # measured in 512-bytes sectors
rootfs_offset=$((esp_size+esp_offset))
# XXX: this is the **file system** UUID, not the **partition** UUID
# Note: this generates the same uuid every time
rootfs_uuid=$(uuidgen --namespace @dns --name ${ROOTFS_LABEL}${BLINUX_BUILD_ID} --md5)

rm -f "$IMG"
truncate -s $((vdisk_size*512)) "$IMG"

cat > ptbl.txt <<-EOF
label: gpt

1: start=${esp_offzet}, size=${esp_size}, type=uefi
2: start=${rootfs_offset}, size=${rootfs_size}, type=${ARCH_ROOTFS_UUID}
EOF

sfdisk --no-reread \
 	--wipe always \
 	--wipe-partition always \
$IMG < ptbl.txt

# Install the boot loader into ESP

cat > build/grub-esp.cfg <<EOF
search.fs_uuid $rootfs_uuid root
set prefix=(\$root)/boot/grub
configfile \$prefix/grub.cfg
EOF


${TARGET}-grub-mkimage \
	--format="${GRUB_ARCH}-efi" \
	--directory="${xtools}${build_prefix}/lib/grub/${GRUB_ARCH}-efi" \
	--output="build/$GRUB_EFI_FILENAME" \
	--prefix="(,gpt2)/boot/grub" \
	--compression='xz' \
	${GRUB_BUILTIN_MODULES} \
	${NIL}

truncate -s $((esp_size*512)) build/esp.img
mkfs.fat -F 16 -n EFISP ./build/esp.img
mmd -i build/esp.img ::EFI
mmd -i build/esp.img ::EFI/BOOT
mmd -i build/esp.img ::EFI/$BOOTLOADER_ID
mcopy -i build/esp.img "build/$GRUB_EFI_FILENAME" ::EFI/$BOOTLOADER_ID/$GRUB_NAME
mcopy -i build/esp.img "build/grub-esp.cfg" ::EFI/$BOOTLOADER_ID/grub.cfg
mcopy -i build/esp.img "build/grub-esp.cfg" ::EFI/BOOT/grub.cfg


for name in $ARCH_EFI_REMOVABLE_NAMES; do
	mcopy -i build/esp.img "build/$GRUB_EFI_FILENAME" ::EFI/BOOT/$name
done

dd if=build/esp.img of=$IMG bs=512 count=${esp_size} conv=notrunc seek=2048


# create boot/grub/grub.cfg for image
kernel_candidate_count=`find "$r00tfs/boot" -type f -name 'vmlinuz*' 2>/dev/null | wc -l`
if test "$kernel_candidate_count" -eq 0; then
	echo "*** Error: distimage: no kernel binaries found" 2>&1
	exit 1
elif test "$kernel_candidate_count" -ge 2; then
	echo "*** Error: several kernel binaries have been found" 2>&1
	exit 1
else
	kernel_bin="`find $r00tfs/boot -type f -name 'vmlinuz*' -printf '%f'`"
fi

mkdir -p -m 755 "$r00tfs/boot/grub"
cat > "$r00tfs/boot/grub/grub.cfg" <<-EOF

set default=boring-gnu-linux-volatile
set timeout=5
set timeout_style=menu
set rootfs_uuid=$rootfs_uuid

menuentry 'Boring GNU/Linux' --class gnu-linux --id boring-gnu-linux {
	insmod linux
	search.fs_uuid \${rootfs_uuid} root
	linux (\$root)/boot/$kernel_bin root=UUID=\${rootfs_uuid} ro systemd.firstboot=no
	initrd (\$root)/boot/initramfs${kernel_bin#vmlinuz}.img
}

menuentry 'Boring GNU/Linux volatile' --class gnu-linux --id boring-gnu-linux-volatile {
	insmod linux
	search.fs_uuid \${rootfs_uuid} root
	linux (\$root)/boot/$kernel_bin root=UUID=\${rootfs_uuid} ro systemd.volatile=overlay systemd.firstboot=no
	initrd (\$root)/boot/initramfs${kernel_bin#vmlinuz}.img
}
EOF

# Create and populate the root filesystem
fakeroot \
mke2fs -v \
	-F \
	-t ext4 \
	-b 4096 \
	-U "$rootfs_uuid" \
	-L "$ROOTFS_LABEL" \
	-O ^has_journal \
	-E offset=$((512*rootfs_offset)),root_owner=0:0 \
	-d "$r00tfs" \
$IMG $((rootfs_size/2))K

cp -al "$IMG" "$IMG_LINK"

sfdisk -l "$IMG"

# RECIPE END distimage
